<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Delegates in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, delegate, .NET, Mono, tutorial, programming language">
<meta name="description" content="This part of the C# tutorial covers C# delegates.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Delegates</h1>

<p>
This part of the C# tutorial is dedicated to delegates. 
</p>

<p>
<b>Delegate</b> A delegate is a form of type-safe function pointer 
used by the .NET Framework. Delegates are often used to implement 
callbacks and event listeners. A delegate does not need to know 
anything about classes of methods it works with. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
A delegate is a reference type. But instead of referring to an object, 
a delegate refers to a method. 
</p>

<p>
Delegates are used in the following cases:
</p>

<ul>
  <li>Event handlers</li>
  <li>Callbacks</li>
  <li>LINQ</li>
  <li>Implementation of design patterns</li>
</ul>


<p>
There is nothing that is done with delegates that cannot be done
with regular methods. Delegates are used, because they bring
several advantages. They foster flexibility of the application
and code reuse. Like interfaces, delegates let us decouple and 
generalize our code. Delegates also allow methods to be passed as parameters.
When we need to decide which method to call at runtime, we use
a delegate. Finally, delegates provide a way of specializing behavior
of a class without subclassing it. Classes may have complex generic behavior, 
but are still meant to be specialized. Classes are specialized either 
through inheritance or via delegates. 
</p>

<h2>Using delegates</h2>

<p>
<b>Simple delegates</b> We will have some simple examples showing, 
how to use delegates.
</p>

<pre class="code">
using System;   


delegate void Mdelegate();

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = new Mdelegate(Callback);
        del();
    }

    static void Callback()
    {
        Console.WriteLine("Calling callback");
    }
}
</pre>

<p>
We declare a delegate, create an instance of the delegate and
invoke it.
</p>

<pre class="explanation">
delegate void Mdelegate();
</pre>

<p>
This is our delegate declaration. It returns no value and takes no 
parameters.
</p>

<pre class="explanation">
Mdelegate del = new Mdelegate(Callback);
</pre>

<p>
We create an instance of the delegate. When called, the delegate will
invoke the static Callback() method. 
</p>

<pre class="explanation">
del();
</pre>

<p>
We call the delegate. 
</p>

<pre>
$ ./simple.exe 
Calling callback
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
<b>Simplified syntax</b> We can use a different syntax for creating and 
using a delegate.
</p>

<pre class="code">
using System;   


delegate void Mdelegate();

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = Callback;
        del();
    }

    static void Callback()
    {
        Console.WriteLine("Calling callback");
    }
} 
</pre>

<p>
We can save some typing when creating an instance of a delegate. 
It was introduces in C# 2.0. 
</p>

<pre class="explanation">
Mdelegate del = Callback;
</pre>

<p>
This is another way of creating a delegate. We save some typing. 
</p>

<hr class="btm">

<p>
<b>Anonymous methods</b> It is possible to use anonymous methods with
delegates. 
</p>

<pre class="code">
using System;   


delegate void Mdelegate();

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = delegate { 
            Console.WriteLine("Anonymous method"); 
        };

        del();
    }
} 
</pre>

<p>
We can omit a method declaration when using an anonymous method
with a delegate. The method has no name and can be invoked only
via the delegate. 
</p>

<pre class="explanation">
Mdelegate del = delegate { 
    Console.WriteLine("Anonymous method"); 
};
</pre>

<p>
Here we create a delegate, that points to an anonymous method. The
anonymous method has a body enclosed by { } characters, but it has 
no name.
</p>

<hr class="btm">

<p>
A delegate can point to different methods over time. 
</p>

<pre class="code">
using System;


public delegate void NameDelegate(string msg);

public class Person 
{
    public string firstName;
    public string secondName;

    public Person(string firstName, string secondName)
    { 
        this.firstName = firstName;
        this.secondName = secondName;
    }

    public void ShowFirstName(string msg)
    {
        Console.WriteLine(msg + this.firstName);
    }

    public void ShowSecondName(string msg)
    {
        Console.WriteLine(msg + this.secondName);
    }
}

public class CSharpApp
{
    public static void Main()
    {
        Person per = new Person("Fabius", "Maximus");       

        NameDelegate nDelegate = new NameDelegate(per.ShowFirstName);
        nDelegate("Call 1: ");

        nDelegate = new NameDelegate(per.ShowSecondName);
        nDelegate("Call 2: ");     
    }
}
</pre>

<p>
In the example we have one delegate. This delegate is used to point
to two methods of the Person class. The methods are called with
the delegate.
</p>

<pre class="explanation">
public delegate void NameDelegate(string msg);
</pre>

<p>
The delegate is created with a <code>delegate</code> keyword.
The delegate signature must match the signature of the method being called
with the delegate.
</p>

<pre class="explanation">
NameDelegate nDelegate = new NameDelegate(per.ShowFirstName);
nDelegate("Call 1: ");
</pre>

<p>
We create an instance of a new delegate, that points to the 
<code>ShowFirstName()</code> method. Later we call the method
via the delegate.
</p>

<pre>
$ ./simpledelegate.exe 
Call 1: Fabius
Call 2: Maximus
</pre>

<p>
Both names are printed via the delegate.
</p>

<hr class="btm">

<p>
<b>Multicast delegate</b> Multicast delegate is a delegate which holds a 
reference to more than one method. Multicast delegates must contain only 
methods that return void, else there is a run-time exception.
</p>

<pre class="code">
using System;   


delegate void Mdelegate(int x, int y);

public class Oper
{
    public static void Add(int x, int y)
    {
        Console.WriteLine("{0} + {1} = {2}", x, y, x + y);
    }

    public static void Sub(int x, int y)
    {
        Console.WriteLine("{0} - {1} = {2}", x, y, x - y);
    }
}

public class CSharpApp
{
    static void Main()
    {
        Mdelegate del = new Mdelegate(Oper.Add);

        del += new Mdelegate(Oper.Sub);
        del(6, 4);            
        del -= new Mdelegate(Oper.Sub);
        del(2, 8);            
    }
}
</pre>

<p>
This is an example of a multicast delegate.  
</p>

<pre class="explanation">
delegate void Mdelegate(int x, int y);
</pre>

<p>
Our delegate will take two parameters. We have
an Oper class, which has two static methods. One
adds two values the other one subtracts two
values.
</p>

<pre class="explanation">
Mdelegate del = new Mdelegate(Oper.Add);
</pre>

<p>
We create an instance of our delegate. The delegate
points to the static Add() method of the Oper class. 
</p>

<pre class="explanation">
del += new Mdelegate(Oper.Sub);
del(6, 4);  
</pre>

<p>
We plug another method to the existing delegate instance. 
The first call of the delegate invokes two methods. 
</p>

<pre class="explanation">
del -= new Mdelegate(Oper.Sub);
del(2, 8);    
</pre>

<p>
We remove one method from the delegate. The second call of the
delegate invokes only one method. 
</p>

<pre>
$ ./multicast.exe 
6 + 4 = 10
6 - 4 = 2
2 + 8 = 10
</pre>

<p>
Output.
</p>

<h2>Delegates as method parameters</h2>

<p>
Delegates can be used as method parameters. 
</p>

<pre class="code">
using System;   


delegate int Arithm(int x, int y);

public class CSharpApp
{
    static void Main()
    {
        DoOperation(10, 2, Multiply);
        DoOperation(10, 2, Divide);
    }

    static void DoOperation(int x, int y, Arithm del)
    {
        int z = del(x, y);
        Console.WriteLine(z);
    }

    static int Multiply(int x, int y)
    {
        return x * y;
    }

    static int Divide(int x, int y)
    {
        return x / y;
    }
} 
</pre>

<p>
We have a DoOperation() method, which takes a delegate as a parameter.
</p>

<pre class="explanation">
delegate int Arithm(int x, int y);
</pre>

<p>
This is a delegate declaration. 
</p>

<pre class="explanation">
static void DoOperation(int x, int y, Arithm del)
{
    int z = del(x, y);
    Console.WriteLine(z);
}
</pre>

<p>
This is DoOperation() method implementation. The third parameter is a 
delegate. The DoOperation() method calls a method, which is passed to 
it as a third parameter. 
</p>

<pre class="explanation">
DoOperation(10, 2, Multiply);
DoOperation(10, 2, Divide);
</pre>

<p>
We call the DoOperation() method. We pass two values and a method to it.
What we do with the two values, depends on the method that we pass. This
is the flexibility that come with using delegates. 
</p>


<h2>Events</h2>

<p>
Events are messages triggered by some action. Click on the button or
tick of a clock are such actions. The object that triggers an event
is called a sender and the object that receives the event is called
a receiver. 
</p>

<p>
By convention, event delegates in the .NET Framework have two parameters, 
the source that raised the event and the data for the event.
</p>


<pre class="code">
using System;   


public delegate void OnFiveHandler(object sender, EventArgs e);

class FEvent { 
    public event OnFiveHandler FiveEvent;
 
    public void OnFiveEvent() 
    { 
        if(FiveEvent != null) 
            FiveEvent(this, EventArgs.Empty); 
    } 
} 

public class CSharpApp
{
    static void Main()
    {
        FEvent fe = new FEvent();
        fe.FiveEvent += new OnFiveHandler(Callback);

        Random random = new Random();

        for (int i = 0; i&lt;10; i++) 
        {
            int rn = random.Next(6);
             
            Console.WriteLine(rn);
            
            if (rn == 5)
            {
                fe.OnFiveEvent();
            }
        }
    }

    public static void Callback(object sender, EventArgs e)
    {
        Console.WriteLine("Five Event occured");
    }
} 
</pre>

<p>
We have a simple example in which we create and launch an event. 
An random number is generated. If the number equals to 5 a FiveEvent
event is generated. 
</p>

<pre class="explanation">
public event OnFiveHandler FiveEvent;
</pre>

<p>
An event is declared with a <code>event</code> keyword.
</p>

<pre class="explanation">
fe.FiveEvent += new OnFiveHandler(Callback);
</pre>

<p>
Here we plug the event called FiveEvent to the 
Callback method. In other words, if the ValueFive
event is triggered, the Callback() method is executed. 
</p>

<pre class="explanation">
public void OnFiveEvent() 
{ 
    if(FiveEvent != null) 
        FiveEvent(this, EventArgs.Empty); 
} 
</pre>

<p>
When the random number equals to 5, we invoke the OnFiveEvent() method.
In this method, we raise the FiveEvent event. This event carries no arguments.
</p>

<pre>
$ ./simpleevent.exe 
3
0
5
Five Event occured
0
5
Five Event occured
2
3
4
4
0
</pre>

<p>
Outcome of the program might look like this.
</p>

<hr class="btm">

<p>
<b>Complex event example</b> Next we have a more complex example. This time we will send some
data with the generated event. 
</p>


<pre class="code">
using System;   


public delegate void OnFiveHandler(object sender, FiveEventArgs e);

public class FiveEventArgs : EventArgs
{
    public int count;
    public DateTime time;

    public FiveEventArgs(int count, DateTime time)
    {
        this.count = count;
        this.time = time;
    }
}

public class FEvent 
{ 
    public event OnFiveHandler FiveEvent;

    public void OnFiveEvent(FiveEventArgs e) 
    { 
        FiveEvent(this, e); 
    } 
} 

public class RandomEventGenerator
{
    public void Generate()
    {
        int count = 0;
        FiveEventArgs args;

        FEvent fe = new FEvent();
        fe.FiveEvent += new OnFiveHandler(Callback);

        Random random = new Random();

        for (int i = 0; i&lt;10; i++) 
        {
            int rn = random.Next(6);
             
            Console.WriteLine(rn);
            
            if (rn == 5)
            {    
                count++;
                args = new FiveEventArgs(count, DateTime.Now);
                fe.OnFiveEvent(args);
            }
        }
    }

    public void Callback(object sender, FiveEventArgs e)
    {
        Console.WriteLine("Five event {0} occured at {1}", 
            e.count, e.time);
    }
}

public class CSharpApp
{
    static void Main()
    {
        RandomEventGenerator reg = new RandomEventGenerator();
        reg.Generate();
    }
} 
</pre>

<p>
We have four classes. FiveEventArgs carries some data with the
event object. The FEvent class encapsulates the event object. RandomEventGenerator class 
is responsible for random number generation. It is the event sender. Finally
the CSharpApp class, which is the main application object and has the Main() method.
</p>

<pre class="explanation">
public class FiveEventArgs : EventArgs
{
    public int count;
    public DateTime time;
...
</pre>

<p>
The FiveEventArgs carries data inside the event object. It inherits from the
<code>EventArgs</code> base class. The count and time members are
data that will be initialized and carried with the event. 
</p>

<pre class="explanation">
if (rn == 5)
{    
    count++;
    args = new FiveEventArgs(count, DateTime.Now);
    fe.OnFiveEvent(args);
}
</pre>

<p>
If the generated random number equals to 5, we instantiate the
FiveEventArgs class with the current count and DateTime values.
The count variable counts the number of times this event was generated.
The DateTime value holds the time, when the event was generated.
</p>


<pre>
$ ./complexevent.exe 
2
2
3
5
Five event 1 occured at 11/7/2010 12:13:59 AM
5
Five event 2 occured at 11/7/2010 12:13:59 AM
1
1
0
5
Five event 3 occured at 11/7/2010 12:13:59 AM
5
Five event 4 occured at 11/7/2010 12:13:59 AM
</pre>

<p>
This is the ouput I got on my computer. 
</p>

<h2>Predefined delegates</h2>

<p>
The .NET framework has several built-in delegates that a reduce the
typing needed and make the programming easier for developers. 
</p>

<p>
<b>Action delegate</b> An action delegate encapsulates a method that 
has no parameters and does not return a value.
</p>

<pre class="code">
using System;   

public class CSharpApp
{
    static void Main()
    {
        Action act = ShowMessage;
        act();
    }

    static void ShowMessage()
    {
        Console.WriteLine("C# language");
    }
} 
</pre>

<p>
Using predefined delegates further simplifies programming. We do not need
to declare a delegate type. 
</p>

<pre class="explanation">
Action act = ShowMessage;
act();
</pre>

<p>
We instantiate an action delegate. The delegate points to the ShowMessage() 
method. When the delegate is invoked, the ShowMessage() method is executed. 
</p>

<hr class="btm">

<p>
<b>Action&lt;T&gt; delegate</b> There are multiple types of action
delegates. For example, the Action&lt;T&gt; delegate encapsulates a 
method that takes a single parameter and does not return a value.
</p>

<pre class="code">
using System;   

public class CSharpApp
{
    static void Main()
    {
        Action&lt;string&gt; act = ShowMessage;
        act("C# language");
    }

    static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }
} 
</pre>

<p>
We modify the previous example to use the action delegate,
that takes one parameter. 
</p>

<pre class="explanation">
Action&lt;string&gt; act = ShowMessage;
act("C# language");
</pre>

<p>
We create an instance of the Action&lt;T&gt; delegate and
call it with one parameter. 
</p>

<hr class="btm">

<p>
<b>Predicate delegate</b> A predicate is a method that returns true or false. 
A predicate delegate is a reference to a predicate. Predicates are very useful 
for filtering a list of values.
</p>

<pre class="code">
using System;
using System.Collections.Generic;

public class CSharpApp
{
    static void Main()
    {
        List&lt;int&gt; list = new List&lt;int&gt; { 4, 2, 3, 0, 6, 7, 1, 9 };

        Predicate&lt;int&gt; predicate = greaterThanThree;

        List&lt;int&gt; list2 = list.FindAll(predicate);

        foreach ( int i in list2)
        {
            Console.WriteLine(i);
        }
    }

    static bool greaterThanThree(int x)
    {
        return x &gt; 3;
    }
}
</pre>

<p>
We have a list of integer values. We want to filter all numbers, that
are bigger than three. For this, we use the predicate delegate. 
</p>

<pre class="explanation">
List&lt;int&gt; list = new List&lt;int&gt; { 4, 2, 3, 0, 6, 7, 1, 9 };
</pre>

<p>
This is a generic list of integer values. 
</p>

<pre class="explanation">
Predicate&lt;int&gt; predicate = greaterThanThree;
</pre>

<p>
We create an instance of a predicate delegate. The delegate
points to a predicate, a special method that returns true
or false.
</p>


<pre class="explanation">
List&lt;int&gt; list2 = list.FindAll(predicate);
</pre>

<p>
The FindAll() method retrieves all the elements that match the 
conditions defined by the specified predicate.
</p>

<pre class="explanation">
static bool greaterThanThree(int x)
{
    return x &gt; 3;
}
</pre>

<p>
The predicate returns true for all values, that are greater than
three. 
</p>

<p>
This part of the C# tutorial was dedicated to the delegates.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified November 1, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
